import { useEffect, useReducer, useState } from 'react';
import { loc_week } from 'sui';

// timer for time's second, example:
/*
    const reducer = (state, action) => {
        if (action.type === "update") {
            handleR();
        }

        return state;
    }

    useTimer(reducer);
*/
const useTimer = (reducer, tick=1000, type="update", data=null) => {
    const [state, dispatch] = useReducer(reducer, {data: data});

    useEffect(() => {
        const id = setInterval(() => dispatch({type: type}), tick);
        return () => {
            clearInterval(id);
        }
    }, [tick, type]);

    return [state, dispatch];
};

const useCur = (def) => {
    const [cur, setCur] = useState(null);
    const [fin, setFin] = useState(def);

    const hcur = (data, d) => {
        setCur(data);
        setFin(d);
    };

    const hreturn = () => setFin(def);

    return [cur, fin, hcur, hreturn];
};

const useWait = () => {
    const [wait, setWait] = useState(false);
    const [wrong, setWrong] = useState(null);

    const startWait = () => {
        setWrong(null);
        setWait(true);
    };

    const endWait = () => {
        setWrong(null);
        setWait(false);
    };

    const setErr = (v) => {
        setWrong(v);
        setWait(false);
    };

    return [wait, wrong, startWait, endWait, setErr];
};

// the current date and time, update per 1s
const useDate = () => {
    const [d, t, w] = loc_week();

    const [date, setDate] = useState(d);
    const [time, setTime] = useState(t);
    const [week, setWeek] = useState(w);

    useEffect(() => {
        const id = setInterval(() => {
            const [cd, ct, cw] = loc_week();
            setDate(cd);
            setTime(ct);
            setWeek(cw);
        }, 1000);

        return () => clearInterval(id);
    }, []);

    return [date, time, week];
};

export {useDate, useWait, useCur, useTimer};
